package com.ruoyi.law_model.knowledge.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.HttpClientUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.law_model.knowledge.Const;
import com.ruoyi.law_model.knowledge.domain.DocumentSplit;
import com.ruoyi.law_model.knowledge.domain.KnowledgeDocuments;
import com.ruoyi.law_model.knowledge.mapper.KnowledgeDocumentsMapper;
import com.ruoyi.law_model.knowledge.service.IDocumentSplitService;
import com.ruoyi.law_model.knowledge.service.IKnowledgeDocumentsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * 存储知识库中的文档信息Service业务层处理
 *
 * @author ruoyi
 * @date 2025-01-10
 */
@Service
public class KnowledgeDocumentsServiceImpl implements IKnowledgeDocumentsService
{
    private static final Logger log = LoggerFactory.getLogger(KnowledgeDocumentsServiceImpl.class);

    private static final Logger logger = LoggerFactory.getLogger(KnowledgeDocumentsServiceImpl.class);

    @Autowired
    private KnowledgeDocumentsMapper knowledgeDocumentsMapper;

    @Autowired
    private IDocumentSplitService documentSplitService;

    @Value("${knowledge.doc_split_host}")
    private String doc_split_host;

    @Value("${knowledge.doc_split_add_url}")
    private String doc_split_add_url;

    @Value("${knowledge.doc_split_del_url}")
    private String doc_split_del_url;

    @Value("${knowledge.doc_split_cookie}")
    private String doc_split_cookie;

    /**
     * 查询存储知识库中的文档信息
     *
     * @param docId 存储知识库中的文档信息主键
     * @return 存储知识库中的文档信息
     */
    @Override
    public KnowledgeDocuments selectKnowledgeDocumentsByDocId(Long docId)
    {
        return knowledgeDocumentsMapper.selectKnowledgeDocumentsByDocId(docId);
    }

    /**
     * 查询存储知识库中的文档信息列表
     *
     * @param knowledgeDocuments 存储知识库中的文档信息
     * @return 存储知识库中的文档信息
     */
    @Override
    public List<KnowledgeDocuments> selectKnowledgeDocumentsList(KnowledgeDocuments knowledgeDocuments)
    {
        return knowledgeDocumentsMapper.selectKnowledgeDocumentsList(knowledgeDocuments);
    }

    /**
     * 新增存储知识库中的文档信息
     *
     * @param knowledgeDocuments 存储知识库中的文档信息
     * @return 结果
     */
    @Override
    public int insertKnowledgeDocuments(KnowledgeDocuments knowledgeDocuments)
    {
        // 拆分文件内容
        Map<String,String> params = new HashMap<>();
        params.put("doc_content",knowledgeDocuments.getContent());
        params.put("file_name",knowledgeDocuments.getDocumentName());
        Const.DOC_MODA_HEADERS.put("Cookie",doc_split_cookie);
        String docResult = HttpClientUtil.doPostJson(doc_split_host+doc_split_add_url,JSONObject.toJSONString(params), Const.DOC_MODA_HEADERS);
        if(StringUtils.isEmpty(docResult)){
            log.info("添加分段失败，返回结果为空");
            return 0;
        }
        // 还原成json对象
        JSONArray jsonArray = JSONArray.parseArray(docResult);
        knowledgeDocumentsMapper.insertKnowledgeDocuments(knowledgeDocuments);
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            DocumentSplit documentSplit = new DocumentSplit();
            documentSplit.setKlId(knowledgeDocuments.getKlId());
            documentSplit.setDocId(knowledgeDocuments.getDocId());
            documentSplit.setSegContent(jsonObject.getString("seg_content"));
            documentSplit.setEmbedId(jsonObject.getString("embed_id"));
            documentSplit.setCreatedAt(new Date());
            documentSplit.setCreatedBy(knowledgeDocuments.getCreatedBy());
            documentSplit.setUpdatedAt(new Date());
            documentSplit.setUpdatedBy(knowledgeDocuments.getUpdatedBy());
            documentSplitService.saveDocumentSplit(documentSplit);
        }
        return 1;
    }

    /**
     * 修改存储知识库中的文档信息
     *
     * @param knowledgeDocuments 存储知识库中的文档信息
     * @return 结果
     */
    @Override
    public int updateKnowledgeDocuments(KnowledgeDocuments knowledgeDocuments)
    {
        return knowledgeDocumentsMapper.updateKnowledgeDocuments(knowledgeDocuments);
    }

    /**
     * 批量删除存储知识库中的文档信息
     *
     * @param docIds 需要删除的存储知识库中的文档信息主键
     * @return 结果
     */
    @Override
    public int deleteKnowledgeDocumentsByDocIds(Long[] docIds)
    {
        //先删除向量数据库
        DocumentSplit documentSplit = new DocumentSplit();
        documentSplit.setDocId(docIds[0]);
        List<DocumentSplit> documentSplitList = documentSplitService.selectDocumentSplitList(documentSplit);
        List<String> embedIds = documentSplitList.stream().map(DocumentSplit::getEmbedId).collect(Collectors.toList());
        Map<String,List<String>> params = new HashMap<>();
        params.put("doc_split_ids",embedIds);
        Const.DOC_MODA_HEADERS.put("Cookie",doc_split_cookie);
        String docResult = HttpClientUtil.doPostJson(doc_split_host+doc_split_del_url,JSONObject.toJSONString(params), Const.DOC_MODA_HEADERS);
        if(! ((embedIds.size() + "\n").equals(docResult))){
            log.info("删除分段失败，返回结果为：{}",docResult);
            return 0;
        }
        return knowledgeDocumentsMapper.deleteKnowledgeDocumentsByDocIds(docIds);
    }

    /**
     * 删除存储知识库中的文档信息信息
     *
     * @param docId 存储知识库中的文档信息主键
     * @return 结果
     */
    @Override
    public int deleteKnowledgeDocumentsByDocId(Long docId)
    {
        return knowledgeDocumentsMapper.deleteKnowledgeDocumentsByDocId(docId);
    }
}
